﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TXTD.Admin.Framework.Reflection
{
    /// <summary>
    /// 反射 模型 工具
    /// </summary>
    public class ReflectionModelUtil
    {
        /// <summary>
        /// 将源数据的值赋值到目标数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <param name="source"></param>
        public static void CopyData<T>(T target, T source)
        {
            //KeyAttribute
            Type type = typeof(T);
            foreach (var item in type.GetProperties())
            {
                var value = item.GetValue(source);
                if (value != null)
                    item.SetValue(target, value);
            }
        }
        /// <summary>
        /// 将源数据的值赋值到目标数据 不同类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target"></param>
        /// <param name="source"></param>
        public static void CopyData<TargetT, SourceT>(TargetT target, SourceT source)
        {
            //KeyAttribute
            Type targetType = typeof(TargetT);
            Type sourceType = typeof(SourceT);
            var sourceProperties = sourceType.GetProperties();
            foreach (var item in targetType.GetProperties())
            {
                var sourceProperty = sourceType.GetProperty(item.Name);
                if (sourceProperty != null)
                {
                    var value = sourceProperty.GetValue(source);
                    if (value != null)
                        item.SetValue(target, value);
                }
            }
        }
        /// <summary>
        /// 将源数据的值赋值到目标数据 不同类   list
        /// </summary>
        /// <typeparam name="TargetT"></typeparam>
        /// <typeparam name="SourceT"></typeparam>
        /// <param name="target"></param>
        /// <param name="source"></param>
        public static List<TargetT> CopyDataList<TargetT, SourceT>(List<SourceT> source)
            where TargetT : new()
        {
            List<TargetT> target = new List<TargetT>();
            foreach (SourceT sourceItem in source)
            {
                TargetT targetItem = new TargetT();
                CopyData(targetItem, sourceItem);
                target.Add(targetItem);
            }
            return target;
        }
    }
}
